﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinHBM.Core.Net.Http;
using WinHBM.Core.Task;
using WinHBM.Test.UI;
using WinHBM.Utils;

namespace WinHBM
{
    static class Program
    {

        private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(typeof(Program));
        private static SynchronizationContext m_SyncContext;
        private static UtilUpdate update;


        static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            Logger.Error("Application_ThreadException:"+e.Exception);
            
        }

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Application.ThreadException += Application_ThreadException;

            if (UtilApp.isRunning())
            {
                MessageBox.Show("无法多次打开该程序");
                Environment.Exit(0);
                return;
            }

            

            try
            {
                m_SyncContext = new SynchronizationContext(); ;
                Thread checkUpdateThread = new Thread(checkUpdate);
                checkUpdateThread.IsBackground = true;
                checkUpdateThread.Start();

                Bootstrap.boot();
                Application.EnableVisualStyles();
                //Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(MainForm.INSTANCE);
                //Application.Run(new TestForm());
                UploadFlowerTask.Start();
            }
            catch (Exception e)
            {
                Logger.Error(e);
                MessageBox.Show("程序终止，异常信息：" + e.Message + "\n" + e.StackTrace);
            }

        }


        private static void checkUpdate()
        {
            update = UtilUpdate.getInstance();
            if (update.checkNetWork() && update.checkNeedUpdate())
            {
                // 主线程弹出提示框
                m_SyncContext.Post(showUpdateDialog, update.newVerson);

                //   update.startUpdate();
                return;
            }
        }

        private static void showUpdateDialog(object versionCode)
        {

            DialogResult dr = MessageBox.Show("更新新版本" + Convert.ToString(versionCode) + "?", " 新版本", MessageBoxButtons.OKCancel);
            if (dr == DialogResult.OK)
            {
                //点确定的代码
                update.startUpdate();
            }
           
        }

    }
}
